package com.yawn.zdweb.controller;

import com.yawn.zdweb.controller.entity.RestResponse;
import com.yawn.zdweb.entity.Group;
import com.yawn.zdweb.user.AuthService;
import com.yawn.zdweb.util.EncryptUtil;
import com.yawn.zdweb.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Created by yawn on 2018-01-26 11:49
 */
@Controller
public class AuthController {

    @Resource
    private AuthService authService;

    @PostMapping("/login")
    @ResponseBody
    public RestResponse login(@RequestBody User loginUser, HttpSession session) {
        String userId = loginUser.getUserId();
        String encryptedPwd = EncryptUtil.md5Encrypt(loginUser.getPassword());
        boolean pwdCheck = authService.checkPwd(userId, encryptedPwd);
        if (pwdCheck) {
            User user = authService.get(userId);
            List<Group> groupList = authService.member(userId);
            session.setAttribute("isLogin", true);
            session.setAttribute("user", user);
            session.setAttribute("userId", user.getId());
            session.setAttribute("groupList", groupList);
            return RestResponse.newInstance(1);
        }
        return RestResponse.newInstance(0, "用户名与密码不匹配！");
    }

    @GetMapping({"/logout", "/exit"})
    public String logout(HttpSession session) {
        session.removeAttribute("isLogin");
        session.removeAttribute("user");
        session.removeAttribute("groupList");
        return "redirect:/default";
    }

}
